package com.eco.fanliapp.controller.app;

import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.AppCompany;
import com.eco.fanliapp.entity.AppUser;
import com.eco.fanliapp.service.IAppNewsLogService;
import com.eco.fanliapp.service.IAppUserService;
import com.eco.fanliapp.service.ITaoBaoService;
import com.eco.fanliapp.service.IUserCashschemeService;
import com.eco.fanliapp.utils.BigDecimalUtils;
import com.eco.fanliapp.utils.JsonUtils;
import com.eco.fanliapp.vo.UserTokenInfo;
import com.taobao.api.internal.util.WebUtils;
import com.taobao.api.response.TbkScPublisherInfoSaveResponse.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/code")
public class CodeController {
	
	private static final Logger log = LoggerFactory.getLogger(CodeController.class);

	@Autowired
	private ITaoBaoService taoBaoService;
	@Autowired
	private IAppUserService iAppUserService;
	@Autowired
	private IAppNewsLogService iAppNewsLogService;
	@Autowired
	private IUserCashschemeService iUserCashschemeService;
	
	/**
	 * 省鸭渠道权限：https://mos.m.taobao.com/inviter/register?inviterCode=9JL63L&src=pub&app=common
	 * 直接拉起手淘：taobao://oauth.taobao.com/authorize?response_type=code&client_id=25355318&redirect_uri=http://47.98.132.55:8892/code/getkey&state=18711111111&view=wap 
	 * web形式：https://oauth.taobao.com/authorize?response_type=code&client_id=25355318&redirect_uri=http://47.98.132.55:8892/code/getkey&state=5&view=web
	 *获取token返回：{"w1_expires_in":1800,"refresh_token_valid_time":1558667540327,"taobao_user_nick":"%E5%AD%99%E4%BA%9A5201314","re_expires_in":2592000,"expire_time":1558667540327,"token_type":"Bearer","access_token":"62009263b0f345edfe47f4dbb6ce6a996bdf082599a9a95840448895","taobao_open_uid":"AAGaOMhSAHV_bLa9BrkDDZMD","w1_valid":1556077340327,"refresh_token":"62008262a303f7458b263ff84e2c76127ceg205b91cc396840448895","w2_expires_in":0,"w2_valid":1556075540327,"r1_expires_in":1800,"r2_expires_in":0,"r2_valid":1556075540327,"r1_valid":1556077340327,"taobao_user_id":"840448895","expires_in":2592000}
	 * @param code
	 * @param state
	 * @return 拿到用户的taoid和access_token
	 * 回调地址：http://47.98.132.55:8892/code/getkey
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping("/getkey")
	@ResponseBody
	private ServerResponse<String> GetAccessToken(String code, String state) {
		log.info("获取的Code值{}",code);
		log.info("获取的state值{}",state);
		String url = "https://oauth.taobao.com/token";
		Map<String, String> props = new HashMap<String, String>();
		props.put("grant_type", "authorization_code");
		props.put("code", code);
		props.put("client_id", ApiEnum.TAO_APPKEY);
		props.put("client_secret", ApiEnum.TAO_SECRET);
		props.put("redirect_uri", "http://47.98.132.55:8892/code/getkey");
		props.put("view", "web");
		String s = "";
		try {
			s = WebUtils.doPost(url, props, 30000, 30000);
			log.info("获取token返回的数据{}",s);
			UserTokenInfo info = JsonUtils.getJsonToBean(s, UserTokenInfo.class);
			if(info != null && info.getAccess_token() != null) {
			AppUser appUser3 = iAppUserService.selectAppUserByUserId(Long.valueOf(state));
			if(appUser3 != null) {
				log.info("获取到的用户数据{}",appUser3.getTableId());
				//RelationId 等于”“或者等于0代表没有渠道ID
				if(appUser3.getRelationId() == 0) {
					AppCompany com = iUserCashschemeService.findCompany(appUser3.getUserId());
					//ServerResponse<Data> response = taoBaoService.getRelationId(com.getInviteCode(), 1, state, info.getAccess_token(), info.getTaobao_user_id());
					ServerResponse<Data> response = taoBaoService.getRelationId2(com.getInviteCode(), info.getAccess_token(), com.getCompanyId().toString(), appUser3.getUserId());
					if(response.getStatus() == 200) {
						 AppUser appUser = new AppUser();
						 appUser.setTableId(appUser3.getTableId());
						 appUser.setRelationId(Long.valueOf(response.getData().getRelationId()));//渠道关系ID
//						 appUser.setRelationId(Long.valueOf(response.getData().getSpecialId()));//会员运营ID
						 appUser.setRelationName(URLDecoder.decode(response.getData().getAccountName()));
						 appUser.setTaobaoOpenUid(info.getTaobao_open_uid());
						 appUser.setTaobaoUserId(info.getTaobao_user_id());
						 appUser.setUserTaobaoAuthorization(2);
						 int i = iAppUserService.updateAppUser(appUser);
						 if(i>0) {
						 	 log.info("用户渠道信息获取正常");
						 	 iAppNewsLogService.newsType(appUser3.getUserId(), 
						 			 NewsEnumLog.NEWS_TAOBAO.getNewsType(),
						 			 BigDecimalUtils.Format(NewsEnumLog.NEWS_TAOBAO.getNewsMoeny()));
							 return ServerResponse.createBySuccessMessage("绑定成功");
						 }else {
							 log.info("用户渠道信息获取失败");
							 return ServerResponse.createByErrorMessage("绑定失败");
						 }
					}else {
						return ServerResponse.createByErrorCodeMessage(response.getStatus(), response.getMsg());
					}
				}else {
					//RelationId不为空或不等于0代表已经获取到渠道ID
					log.info("用户重复授权--获取到的用户渠道ID为{}",appUser3.getRelationId());
					return ServerResponse.createBySuccessMessage("您已经授权过了，快去购物吧");
				}
			}else {
				return ServerResponse.createByErrorMessage("请先登陆");
			}
		}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ServerResponse.createByErrorMessage("用户信息获取失败");
	}
	
}
